Download File
Description
The download_file
function downloads a file from a given URL and saves it to a specified local file path. It supports automatic retries up to 5 times in case of failures.
Function Signature:
def download_file(file_path: str, url: str) -> int:
Parameters
- file_path (
str
): The local path where the file should be saved. - url (
str
): The URL from which the file will be downloaded.
Returns
- int: The result of the download operation:
0
: Success-2
: Exception occurred while downloading file-3
: Retry limit exceeded
Example Usage
file_path = "path/to/your/downloaded_file.txt"
url = "https://example.com/file-to-download"
result = download_file(file_path, url)
if result == 0:
print("File downloaded successfully")
else:
print(f"File download failed with result code: {result}")
Notes
- The function attempts to download the file up to 5 times in case of failure (e.g., network errors or server issues).
- The file is downloaded in chunks (8 KB at a time) to optimize memory usage.
- If the retry count exceeds 5, the function returns
-3
. - The
raise_for_status()
method is used to check for HTTP errors (e.g., 404 or 500).
Error Handling
- If the file download fails due to an exception (e.g., network issue), the function prints the error message and retries the download.
- If the retry count exceeds 5, the function will stop retrying and return
-3
.